package com.caigou.modules.info.ui.myself

import android.os.Bundle
import android.view.MotionEvent
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.modules.info.adapter.MyInfoPagerAdapter
import com.caigou.modules.info.databinding.ActivityMyInfoBinding
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import java.util.*

/**
 * @author #Suyghur.
 * Created on 2021/11/20
 */
@Route(path = RouterPath.Info.PAGE_MY_INFO)
@AndroidEntryPoint
class MyInfoActivity : BaseActivity() {

    private lateinit var binding: ActivityMyInfoBinding
    private val itemNames = mutableListOf(
        "我的资料",
        "已收藏"
    )

    private val fragments = mutableListOf<Fragment>(
        MyInfoFragment(),
        MyCollectedFragment()
    )

    private val infoPagerAdapter: MyInfoPagerAdapter by lazy {
        MyInfoPagerAdapter(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMyInfoBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.myInfoLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)

        binding.myInfoViewPager2.adapter = infoPagerAdapter
        binding.myInfoViewPager2.isUserInputEnabled = false
        TabLayoutMediator(binding.myInfoTabLayout, binding.myInfoViewPager2, true, true) { tab, position ->
            tab.text = itemNames[position]
        }.attach()
        infoPagerAdapter.setList(fragments)
        binding.myInfoViewPager2.offscreenPageLimit = itemNames.size

        binding.myInfoTvBack.setOnClickListener {
            finish()
        }
    }


    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        ev?.let {
            if (it.action == MotionEvent.ACTION_DOWN) {
                val v = currentFocus
                if (isShouldHideInput(v, it)) {
                    val imm =
                        this@MyInfoActivity.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.hideSoftInputFromWindow(v!!.windowToken, 0)
                }
                return super.dispatchTouchEvent(it)
            }
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return if (window.superDispatchTouchEvent(ev)) {
            true
        } else onTouchEvent(ev)
    }

    override fun onBackPressed() {
        if (fragmentStack.isNotEmpty() && fragmentStack.size > 1) {
            fragmentStack.removeLast()
            switchFragment(fragmentStack.last)
        } else {
            super.onBackPressed()
        }
    }

}